<?php
 
//获取用户ip(外网ip 服务器上可以获取用户外网Ip 本机ip地址只能获取127.0.0.1)
function getip(){
    if(!empty($_SERVER["HTTP_CLIENT_IP"])){
    $cip = $_SERVER["HTTP_CLIENT_IP"];
    }
    else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
    $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    else if(!empty($_SERVER["REMOTE_ADDR"])){
    $cip = $_SERVER["REMOTE_ADDR"];
    }
    else{
    $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
    unset($cips);
    return $cip;
}
 
$ip=getip();
 
//根据百度地图api得到用户Ip地理经纬度和城市
 
$url = "http://api.map.baidu.com/location/ip?ak=omi69HPHpl5luMtrjFzXn9df&ip=$ip&coor=bd09ll";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
if(curl_errno($ch))
{ echo 'CURL ERROR Code: '.curl_errno($ch).', reason: '.curl_error($ch);}
curl_close($ch);
$info = json_decode($output, true);
if($info['status'] == "0"){
    $lotx = $info['content']['point']['y'];
    $loty = $info['content']['point']['x'];
    $citytemp = $info['content']['address_detail']['city'];
    $keywords = explode("市",$citytemp);
    $city = $keywords[0];
}
 
 
var_dump($lotx);//x坐标  纬度
var_dump($loty);//y坐标  经度
var_dump($city);//用户Ip所在城市


function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);

}

// 起点坐标
$longitude1 = $loty;
$latitude1 = $lotx;


// 终点坐标 商友坐标
$longitude2 = 113.398849;
$latitude2 = 22.510816;

$distance = getDistance($longitude1, $latitude1, $longitude2, $latitude2, 1);
echo $distance.'m'; // 2342.38m

$distance = getDistance($longitude1, $latitude1, $longitude2, $latitude2, 2);
echo $distance.'km'; // 2.34km